//
//  MainViewController.m
//  ApexCardSDK_Demo_iOS
//
//  Created by 谭永明 on 16/9/24.
//  Copyright © 2016年 珠海艾派克科技股份有限公司. All rights reserved.
//

#import "MainViewController.h"
#import <SystemConfiguration/CaptiveNetwork.h>

#import "WriteCardTableViewController.h"
#import "ReadCardTableViewController.h"

@interface MainViewController ()<DeviceConnectListener, CardListener, MCCardFileWriteDelegate, MCCardFileReaderDelegate>

@property (nonatomic, strong) MCDevice *device;

@property (nonatomic, weak) WriteCardTableViewController *writeCardVC;

@property (nonatomic, weak) ReadCardTableViewController *readCardVC;

@property (weak, nonatomic) IBOutlet UILabel *connectDeviceLabel;

@property (nonatomic, assign) BOOL needWriteCard;



@property (nonatomic, strong) NSMutableArray *readFileArray;

@property (nonatomic, strong) MCCard *readCard;

@property (nonatomic, assign) BOOL needReadCard;

@property (nonatomic, assign) BOOL readingCard;

@property (nonatomic, assign) NSInteger readCardFileIndex;

@end

@implementation MainViewController

#pragma mark - lazy

-(MCDevice *)device {
    if (!_device) {
        _device = [MCDriverFactory sharedInstance].device;
        _device.deviceConnectListener = self;
        _device.cardListener = self;
        _device.cardFileWriter.delegate = self;
        _device.cardFileReader.delegate = self;
    }
    return _device;
}

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addViewControllers];
}

-(void)addViewControllers {
    WriteCardTableViewController *writeCardVC = [[WriteCardTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    
    [self addChildViewController:writeCardVC];
    self.writeCardVC = writeCardVC;
    
    
    ReadCardTableViewController *readCardVC = [[ReadCardTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    [self addChildViewController:readCardVC];
    self.readCardVC = readCardVC;
}

#pragma mark - action

- (IBAction)writeBtnClick:(UIButton *)sender {
    
    if (self.device != nil) {
        
        // 检查连接情况
        if ([self checkWiFiDeviceConnection]) {
            
            // 设置为写卡模式
            [self.device setMode:MCDeviceMode_WRITE_ONLY];
            
            self.writeCardVC.device = self.device;
            
            UIView *writeView = self.writeCardVC.view;
            writeView.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64);
            writeView.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:writeView];
            
            [self.writeCardVC writeCard];
            
            // 添加返回按钮
            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(writeActionBack)];
            
            self.needWriteCard = NO;
            
        } else {
            self.needWriteCard = YES;
        }
        
    } else {
        
        [self createDevice];
        [self writeBtnClick:nil];
        
    }
    
}

- (IBAction)readBtnClick:(UIButton *)sender {
    if (self.device != nil) {
        
        if ([self checkWiFiDeviceConnection]) {
            
            // 设置为读卡模式
            [self.device setMode:MCDeviceMode_READ_ONLY];
            
            if (self.readFileArray.count <= 0) {
                self.needReadCard = YES;
                return;
            }
            
            NSArray *filesList = self.readFileArray;
            
            self.readCardVC.card = self.readCard;
            
            NSInteger totalSize = 0;
            for (MCCardFile *cardFile in filesList) {
                totalSize += cardFile.length / 1024;
            }
            self.readCardVC.totalSize = totalSize;
            
            self.readCardVC.files = filesList;
            
            UIView *readView = self.readCardVC.view;
            readView.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64);
            readView.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:readView];
            
            
            self.readingCard = YES;
            
            self.readCardFileIndex = 0;
            
            
            // 开始读卡
            [self.device.cardFileReader read:self.readFileArray[self.readCardFileIndex]];
            
            
            // 添加返回按钮
            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(readActionBack)];
            
            
            
            self.needReadCard = NO;
            
        } else {
            
            self.needReadCard = YES;
            
        }
        
    } else {
        
        [self createDevice];
        [self readBtnClick:nil];
        
    }

}

- (IBAction)setBtnClick:(UIButton *)sender {
    // 读卡器连接失败，是否重新连接？
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"读卡器连接失败，请检查Wi-Fi和读卡器工作状态并且重新连接" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    WeakSelf;
    
    // 取消
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    // 去设置
    UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:@"prefs:root=WIFI"];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url];
        }
    }];
    [alertController addAction:doneAction];
    
    // 重新连接
    UIAlertAction *reConnectAction = [UIAlertAction actionWithTitle:@"重新连接" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf connectDevice];
    }];
    [alertController addAction:reConnectAction];
    
    [self.navigationController presentViewController:alertController animated:NO completion:nil];
}

#pragma mark - DeviceConnectListener

- (void)onDeviceConnected:(MCDeviceConnectEvent *)event {
    [self setStatusText:@"连接设备成功"];
    [self.connectDeviceLabel setText:[NSString stringWithFormat:@"连接设备 : %@", [self getWifiName]]];
}

- (void)onDeviceDisconnect:(MCDeviceConnectEvent *)event {
    [self setStatusText:@"连接设备失败"];
    [self setBtnClick:nil];
}

#pragma mark - CardListener

- (void)onCardAttached:(MCCardEvent *)event {
    [self setStatusText:@"卡片靠近了"];
}

- (void)onCardUnattached:(MCCardEvent *)event {
    [self setStatusText:@"卡片远离了"];
}

- (void)onCardChanged:(MCCardEvent *)event {

    [self setStatusText:@"onCardChanged"];
    
    if (self.needWriteCard) {
        [self writeBtnClick:nil];
        self.needWriteCard = NO;
        return;
    }
    
    self.readCard = event.NewCard;
    self.readFileArray = event.NewCard.listFile;

    if (self.needReadCard) {
        [self readBtnClick:nil];
        self.needReadCard = NO;
    }
}

- (void)onCardNotApplicable:(MCCardEvent *)event {
    [self setStatusText:@"onCardNotApplicable"];
}

- (void)onCardTotalProgress:(MCCardEvent *)event {
    [self setStatusText:[NSString stringWithFormat:@"读卡进度 : %.2f %%", 1.0 * event.currentAmount / event.targetAmount * 100]];
}

- (void)onCardTotalFinished:(MCCardEvent *)event {
    [self setStatusText:@"读卡操作完成"];
    self.readingCard = NO;
    self.readCardFileIndex = 0;
}

#pragma mark - MCCardFileWriteDelegate

- (void)onCardWriteDidStarted:(MCCardWriteEvent *)event {
    [self setStatusText:@"开始写卡操作"];
}

- (void)onCardWriteProgress:(MCCardWriteEvent *)event {
    [self setStatusText:[NSString stringWithFormat:@"写卡进度 : %.2f %%", (event.rateOfProgress * 100)]];
}

- (void)onCardWriteDidFinished:(MCCardWriteEvent *)event {
    [self setStatusText:@"完成写卡操作"];
}

#pragma mark - MCCardFileReaderDelegate

- (void)onCardReadDidStarted:(MCCardReadEvent *)event {
    [self setStatusText:@"开始读卡"];
}

- (void)onCardReadProgress:(MCCardReadEvent *)event {
    if (self.readingCard) {
        self.readFileArray[self.readCardFileIndex] = event.cardFile;
        [self.readCardVC updateFileProgressWithFileIndex:self.readCardFileIndex withCardFile:event.cardFile];
    }
}

- (void)onCardReadDidFinished:(MCCardReadEvent *)event {
    if (self.readingCard) {
        self.readFileArray[self.readCardFileIndex] = event.cardFile;
        [self.readCardVC updateFileProgressWithFileIndex:self.readCardFileIndex withCardFile:event.cardFile];
        
        self.readCardFileIndex++;
        if (self.readCardFileIndex < self.readFileArray.count) {
            [self.device.cardFileReader read:self.readFileArray[self.readCardFileIndex]];
        }
    }
}

#pragma mark - private methods

// 创建连接设备
-(void)createDevice {
    MCWiFiDevice *device = [[MCWiFiDevice alloc] init];//初始化WIFI设备
    [[MCDriverFactory sharedInstance] registryDevice:device];//注册WIFI设备
}

// 连接设备
-(void)connectDevice {
    if (self.device == nil) {
        [self createDevice];
    }
    [(MCWiFiDevice *)self.device startConnect];
    [self setStatusText:@"开始尝试连接设备ing..."];
}

-(void)writeActionBack {
    [self.device.cardFileWriter close];
    [self.writeCardVC.view removeFromSuperview];
    self.navigationItem.leftBarButtonItem = nil;
}

-(void)readActionBack {
    [self.device.cardFileReader close];
    [self.readCardVC.view removeFromSuperview];
    self.navigationItem.leftBarButtonItem = nil;
}

-(BOOL)checkWiFiDeviceConnection {
    if (self.device.isEnable) {
        if (self.device.isCardAttached) {
            return YES;
        } else {
            [self setStatusText:@"请靠近卡片"];
            return NO;
        }
    } else {
        [self connectDevice];
        return NO;
    }
}

-(void)setStatusText:(NSString *)text {
    self.navigationItem.title = text;
}

- (NSString *)getWifiName {
    NSString *wifiName = nil;
    
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        return nil;
    }
    
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            CFRelease(dictRef);
        }
    }
    
    CFRelease(wifiInterfaces);
    return wifiName;
}

@end
